import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

// 基础体温记录模型
class BasalBodyTemperature {
  final int? id;
  final DateTime date;
  final double temperature; // 基础体温，摄氏度
  final String? timeRecorded; // 记录时间，HH:MM格式
  final bool? isOvulationDay; // 是否可能排卵日
  final String? notes;
  final int userId;

  BasalBodyTemperature({
    this.id,
    required this.date,
    required this.temperature,
    this.timeRecorded,
    this.isOvulationDay,
    this.notes,
    required this.userId,
  });

  Map<String, dynamic> toMap() {
    return {
      'date': DateFormat('yyyy-MM-dd').format(date),
      'temperature': temperature,
      'timeRecorded': timeRecorded,
      'isOvulationDay': isOvulationDay == true ? 1 : 0,
      'notes': notes,
      'userId': userId,
    };
  }

  factory BasalBodyTemperature.fromMap(Map<String, dynamic> map) {
    return BasalBodyTemperature(
      id: map['id'],
      date: DateTime.parse(map['date']),
      temperature: map['temperature'],
      timeRecorded: map['timeRecorded'],
      isOvulationDay: map['isOvulationDay'] == 1,
      notes: map['notes'],
      userId: map['userId'],
    );
  }

  // 比较是否比另一个温度高
  bool isHigherThan(BasalBodyTemperature other) {
    return temperature > other.temperature;
  }

  // 获取温度趋势图标
  IconData getTrendIcon(BasalBodyTemperature? previous) {
    if (previous == null) return Icons.arrow_right;
    if (temperature > previous.temperature + 0.3) return Icons.trending_up;
    if (temperature < previous.temperature - 0.3) return Icons.trending_down;
    return Icons.arrow_right;
  }

  // 获取温度趋势描述
  String getTrendDescription(BasalBodyTemperature? previous) {
    if (previous == null) return '首次记录';
    final difference = temperature - previous.temperature;
    if (difference > 0.3) return '明显升高';
    if (difference > 0.1) return '轻微升高';
    if (difference < -0.3) return '明显降低';
    if (difference < -0.1) return '轻微降低';
    return '基本稳定';
  }
}

// 排卵试纸记录模型
class OvulationTest {
  final int? id;
  final DateTime date;
  final String result; // 'negative', 'light', 'medium', 'strong', 'positive'
  final String? imagePath; // 存储图像的本地路径
  final int lineIntensity; // 1-10，表示线条强度
  final String? notes;
  final int userId;

  OvulationTest({
    this.id,
    required this.date,
    required this.result,
    this.imagePath,
    this.lineIntensity = 5,
    this.notes,
    required this.userId,
  });

  Map<String, dynamic> toMap() {
    return {
      'date': DateFormat('yyyy-MM-dd').format(date),
      'result': result,
      'imagePath': imagePath,
      'lineIntensity': lineIntensity,
      'notes': notes,
      'userId': userId,
    };
  }

  factory OvulationTest.fromMap(Map<String, dynamic> map) {
    return OvulationTest(
      id: map['id'],
      date: DateTime.parse(map['date']),
      result: map['result'],
      imagePath: map['imagePath'],
      lineIntensity: map['lineIntensity'],
      notes: map['notes'],
      userId: map['userId'],
    );
  }

  // 获取结果文本描述
  String getResultText() {
    switch (result) {
      case 'negative': return '阴性';
      case 'light': return '弱阳性';
      case 'medium': return '中等强度';
      case 'strong': return '强阳性';
      case 'positive': return '阳性（LH峰值）';
      default: return '未知结果';
    }
  }

  // 获取结果颜色
  Color getResultColor() {
    switch (result) {
      case 'negative': return Colors.grey.shade400;
      case 'light': return Colors.yellow.shade600;
      case 'medium': return Colors.orange.shade500;
      case 'strong': return Colors.pink.shade500;
      case 'positive': return Colors.red.shade600;
      default: return Colors.grey.shade400;
    }
  }

  // 判断是否处于LH峰值
  bool isPeakDay() {
    return result == 'positive' || result == 'strong';
  }
}

// 同房记录模型
class Intercourse {
  final int? id;
  final DateTime date;
  final String? time; // 可选时间记录
  final int satisfaction; // 1-5表示满意度
  final bool protectionUsed; // 是否使用避孕措施
  final String? notes;
  final int userId;

  Intercourse({
    this.id,
    required this.date,
    this.time,
    this.satisfaction = 3,
    this.protectionUsed = false,
    this.notes,
    required this.userId,
  });

  Map<String, dynamic> toMap() {
    return {
      'date': DateFormat('yyyy-MM-dd').format(date),
      'time': time,
      'satisfaction': satisfaction,
      'protectionUsed': protectionUsed ? 1 : 0,
      'notes': notes,
      'userId': userId,
    };
  }

  factory Intercourse.fromMap(Map<String, dynamic> map) {
    return Intercourse(
      id: map['id'],
      date: DateTime.parse(map['date']),
      time: map['time'],
      satisfaction: map['satisfaction'],
      protectionUsed: map['protectionUsed'] == 1,
      notes: map['notes'],
      userId: map['userId'],
    );
  }
}

// 宫颈粘液记录模型
class CervicalMucus {
  final int? id;
  final DateTime date;
  final String consistency; // 'dry', 'sticky', 'creamy', 'watery', 'eggwhite'
  final String color; // 'clear', 'white', 'yellowish', 'brownish'
  final String amount; // 'none', 'light', 'medium', 'heavy'
  final String? notes;
  final int userId;

  CervicalMucus({
    this.id,
    required this.date,
    required this.consistency,
    this.color = 'clear',
    this.amount = 'medium',
    this.notes,
    required this.userId,
  });

  Map<String, dynamic> toMap() {
    return {
      'date': DateFormat('yyyy-MM-dd').format(date),
      'consistency': consistency,
      'color': color,
      'amount': amount,
      'notes': notes,
      'userId': userId,
    };
  }

  factory CervicalMucus.fromMap(Map<String, dynamic> map) {
    return CervicalMucus(
      id: map['id'],
      date: DateTime.parse(map['date']),
      consistency: map['consistency'],
      color: map['color'],
      amount: map['amount'],
      notes: map['notes'],
      userId: map['userId'],
    );
  }

  // 获取受孕友好度评分 (1-10)
  int getFertilityScore() {
    switch (consistency) {
      case 'eggwhite': return 10;
      case 'watery': return 8;
      case 'creamy': return 5;
      case 'sticky': return 3;
      case 'dry': return 1;
      default: return 5;
    }
  }

  // 获取描述文本
  String getDescription() {
    String consistencyText;
    switch (consistency) {
      case 'dry': consistencyText = '干燥';
      case 'sticky': consistencyText = '粘稠';
      case 'creamy': consistencyText = '乳状';
      case 'watery': consistencyText = '水样';
      case 'eggwhite': consistencyText = '蛋清状';
      default: consistencyText = '未知';
    }

    String colorText;
    switch (color) {
      case 'clear': colorText = '透明';
      case 'white': colorText = '白色';
      case 'yellowish': colorText = '淡黄色';
      case 'brownish': colorText = '淡棕色';
      default: colorText = '未知';
    }

    String amountText;
    switch (amount) {
      case 'none': amountText = '无';
      case 'light': amountText = '少量';
      case 'medium': amountText = '中等';
      case 'heavy': amountText = '较多';
      default: amountText = '未知';
    }

    return '$colorText$consistencyText，$amountText';
  }
}

// 生育预测结果模型
class FertilityPrediction {
  final DateTime predictedOvulationDate;
  final List<DateTime> fertileWindow;
  final DateTime bestIntercourseDay;
  final double peakProbability;
  final int predictionConfidence; // 0-100的置信度
  final List<String> predictionFactors;
  final String recommendation;

  FertilityPrediction({
    required this.predictedOvulationDate,
    required this.fertileWindow,
    required this.bestIntercourseDay,
    required this.peakProbability,
    required this.predictionConfidence,
    this.predictionFactors = const [],
    this.recommendation = '',
  });

  // 获取特定日期的受孕概率
  double getPregnancyProbabilityForDate(DateTime date) {
    final daysUntilOvulation = predictedOvulationDate.difference(date).inDays;
    
    if (daysUntilOvulation == 0) return peakProbability; // 排卵日
    if (daysUntilOvulation == 1) return peakProbability * 0.8; // 排卵前一天
    if (daysUntilOvulation == 2) return peakProbability * 0.6; // 排卵前两天
    if (daysUntilOvulation == -1) return peakProbability * 0.7; // 排卵后一天
    
    // 其他易孕期
    if (fertileWindow.contains(date)) {
      return peakProbability * 0.4;
    }
    
    return 0.05; // 非易孕期基础概率
  }

  // 获取置信度文本
  String getConfidenceText() {
    if (predictionConfidence >= 90) return '非常高';
    if (predictionConfidence >= 75) return '较高';
    if (predictionConfidence >= 60) return '中等';
    if (predictionConfidence >= 40) return '较低';
    return '很低';
  }

  // 获取置信度颜色
  Color getConfidenceColor() {
    if (predictionConfidence >= 90) return Colors.green.shade700;
    if (predictionConfidence >= 75) return Colors.green.shade500;
    if (predictionConfidence >= 60) return Colors.yellow.shade600;
    if (predictionConfidence >= 40) return Colors.orange.shade500;
    return Colors.red.shade500;
  }
}

// 备孕知识库文章模型
class PregnancyKnowledgeArticle {
  final int id;
  final String title;
  final String category; // 'nutrition', 'checkup', 'lifestyle', 'fertility'
  final String content;
  final String? summary;
  final String? imagePath;
  final List<String>? tags;
  final DateTime createdAt;
  final int readCount;
  final double rating; // 1-5分

  PregnancyKnowledgeArticle({
    required this.id,
    required this.title,
    required this.category,
    required this.content,
    this.summary,
    this.imagePath,
    this.tags = const [],
    required this.createdAt,
    this.readCount = 0,
    this.rating = 0,
  });

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'title': title,
      'category': category,
      'content': content,
      'summary': summary,
      'imagePath': imagePath,
      'tags': tags?.join(',') ?? '',
      'createdAt': createdAt.toIso8601String(),
      'readCount': readCount,
      'rating': rating,
    };
  }

  factory PregnancyKnowledgeArticle.fromMap(Map<String, dynamic> map) {
    return PregnancyKnowledgeArticle(
      id: map['id'],
      title: map['title'],
      category: map['category'],
      content: map['content'],
      summary: map['summary'],
      imagePath: map['imagePath'],
      tags: map['tags'] is String 
          ? (map['tags'] as String).split(',').where((t) => t.isNotEmpty).toList() 
          : const [],
      createdAt: DateTime.parse(map['createdAt']),
      readCount: map['readCount'],
      rating: map['rating'],
    );
  }

  // 获取分类文本
  String getCategoryText() {
    switch (category) {
      case 'nutrition': return '营养饮食';
      case 'checkup': return '孕前检查';
      case 'lifestyle': return '生活方式';
      case 'fertility': return '生育健康';
      default: return '其他';
    }
  }

  // 获取分类颜色
  Color getCategoryColor() {
    switch (category) {
      case 'nutrition': return Colors.green.shade600;
      case 'checkup': return Colors.blue.shade600;
      case 'lifestyle': return Colors.purple.shade600;
      case 'fertility': return Colors.pink.shade600;
      default: return Colors.grey.shade600;
    }
  }
}

// 健康指标模型
class HealthMetrics {
  final int? id;
  final DateTime date;
  final double? weight; // 体重(kg)
  final double? bmi; // BMI指数
  final int? bloodPressureSystolic; // 收缩压
  final int? bloodPressureDiastolic; // 舒张压
  final int? heartRate; // 心率
  final double? bloodGlucose; // 血糖(mmol/L)
  final double? vitaminD; // 维生素D水平
  final double? folicAcid; // 叶酸水平
  final String? notes;
  final int userId;

  HealthMetrics({
    this.id,
    required this.date,
    this.weight,
    this.bmi,
    this.bloodPressureSystolic,
    this.bloodPressureDiastolic,
    this.heartRate,
    this.bloodGlucose,
    this.vitaminD,
    this.folicAcid,
    this.notes,
    required this.userId,
  });

  Map<String, dynamic> toMap() {
    return {
      'date': DateFormat('yyyy-MM-dd').format(date),
      'weight': weight,
      'bmi': bmi,
      'bloodPressureSystolic': bloodPressureSystolic,
      'bloodPressureDiastolic': bloodPressureDiastolic,
      'heartRate': heartRate,
      'bloodGlucose': bloodGlucose,
      'vitaminD': vitaminD,
      'folicAcid': folicAcid,
      'notes': notes,
      'userId': userId,
    };
  }

  factory HealthMetrics.fromMap(Map<String, dynamic> map) {
    return HealthMetrics(
      id: map['id'],
      date: DateTime.parse(map['date']),
      weight: map['weight'],
      bmi: map['bmi'],
      bloodPressureSystolic: map['bloodPressureSystolic'],
      bloodPressureDiastolic: map['bloodPressureDiastolic'],
      heartRate: map['heartRate'],
      bloodGlucose: map['bloodGlucose'],
      vitaminD: map['vitaminD'],
      folicAcid: map['folicAcid'],
      notes: map['notes'],
      userId: map['userId'],
    );
  }

  // 获取血压状态
  String getBloodPressureStatus() {
    if (bloodPressureSystolic == null || bloodPressureDiastolic == null) {
      return '未知';
    }
    
    // 在null检查后使用非空断言
    final systolic = bloodPressureSystolic!;
    final diastolic = bloodPressureDiastolic!;
    
    if (systolic < 120 && diastolic < 80) {
      return '正常';
    } else if (systolic < 130 && diastolic < 85) {
      return '正常高值';
    } else if (systolic < 140 || diastolic < 90) {
      return '高血压前期';
    } else if (systolic < 160 || diastolic < 100) {
      return '轻度高血压';
    } else if (systolic < 180 || diastolic < 110) {
      return '中度高血压';
    } else {
      return '重度高血压';
    }
  }
}

// 叶酸补充记录模型
class FolicAcidIntake {
  final int? id;
  final DateTime date;
  final double amount; // 摄入量(μg)
  final bool taken; // 是否已服用
  final String? notes;
  final int userId;

  FolicAcidIntake({
    this.id,
    required this.date,
    this.amount = 400.0, // 标准剂量400μg
    this.taken = false,
    this.notes,
    required this.userId,
  });

  Map<String, dynamic> toMap() {
    return {
      'date': DateFormat('yyyy-MM-dd').format(date),
      'amount': amount,
      'taken': taken ? 1 : 0,
      'notes': notes,
      'userId': userId,
    };
  }

  factory FolicAcidIntake.fromMap(Map<String, dynamic> map) {
    return FolicAcidIntake(
      id: map['id'],
      date: DateTime.parse(map['date']),
      amount: map['amount'],
      taken: map['taken'] == 1,
      notes: map['notes'],
      userId: map['userId'],
    );
  }
}

// 备孕设置模型
class PregnancyPrepSettings {
  final int userId;
  final bool temperatureReminderEnabled;
  final String temperatureReminderTime; // HH:MM格式
  final bool intercourseReminderEnabled;
  final int intercourseFrequencyGoal; // 每周目标次数
  final bool fertilityWindowNotificationEnabled;
  final bool ovulationTestReminderEnabled;
  final String preferredTrackingMethods; // 逗号分隔的跟踪方法列表

  PregnancyPrepSettings({
    required this.userId,
    this.temperatureReminderEnabled = true,
    this.temperatureReminderTime = '07:00',
    this.intercourseReminderEnabled = true,
    this.intercourseFrequencyGoal = 3,
    this.fertilityWindowNotificationEnabled = true,
    this.ovulationTestReminderEnabled = true,
    this.preferredTrackingMethods = 'temperature,ovulation_test,cervical_mucus',
  });

  Map<String, dynamic> toMap() {
    return {
      'userId': userId,
      'temperatureReminderEnabled': temperatureReminderEnabled ? 1 : 0,
      'temperatureReminderTime': temperatureReminderTime,
      'intercourseReminderEnabled': intercourseReminderEnabled ? 1 : 0,
      'intercourseFrequencyGoal': intercourseFrequencyGoal,
      'fertilityWindowNotificationEnabled': fertilityWindowNotificationEnabled ? 1 : 0,
      'ovulationTestReminderEnabled': ovulationTestReminderEnabled ? 1 : 0,
      'preferredTrackingMethods': preferredTrackingMethods,
    };
  }

  factory PregnancyPrepSettings.fromMap(Map<String, dynamic> map) {
    return PregnancyPrepSettings(
      userId: map['userId'],
      temperatureReminderEnabled: map['temperatureReminderEnabled'] == 1,
      temperatureReminderTime: map['temperatureReminderTime'],
      intercourseReminderEnabled: map['intercourseReminderEnabled'] == 1,
      intercourseFrequencyGoal: map['intercourseFrequencyGoal'],
      fertilityWindowNotificationEnabled: map['fertilityWindowNotificationEnabled'] == 1,
      ovulationTestReminderEnabled: map['ovulationTestReminderEnabled'] == 1,
      preferredTrackingMethods: map['preferredTrackingMethods'],
    );
  }

  // 获取首选跟踪方法列表
  List<String> getPreferredTrackingMethodsList() {
    return preferredTrackingMethods.split(',').where((method) => method.isNotEmpty).toList();
  }
}

// 备孕进度模型
class PregnancyPrepProgress {
  final int userId;
  final int consecutiveDaysTracking; // 连续跟踪天数
  final int totalDaysTracking; // 总跟踪天数
  final int completedCheckups; // 已完成的检查项目数
  final int totalCheckups; // 总检查项目数
  final double folicAcidComplianceRate; // 叶酸服用依从率
  final double averageCycleRegularity; // 平均周期规律性
  final DateTime lastProgressUpdate; // 上次进度更新时间

  PregnancyPrepProgress({
    required this.userId,
    this.consecutiveDaysTracking = 0,
    this.totalDaysTracking = 0,
    this.completedCheckups = 0,
    this.totalCheckups = 10, // 默认10项检查
    this.folicAcidComplianceRate = 0.0,
    this.averageCycleRegularity = 0.0,
    required this.lastProgressUpdate,
  });

  Map<String, dynamic> toMap() {
    return {
      'userId': userId,
      'consecutiveDaysTracking': consecutiveDaysTracking,
      'totalDaysTracking': totalDaysTracking,
      'completedCheckups': completedCheckups,
      'totalCheckups': totalCheckups,
      'folicAcidComplianceRate': folicAcidComplianceRate,
      'averageCycleRegularity': averageCycleRegularity,
      'lastProgressUpdate': lastProgressUpdate.toIso8601String(),
    };
  }

  factory PregnancyPrepProgress.fromMap(Map<String, dynamic> map) {
    return PregnancyPrepProgress(
      userId: map['userId'],
      consecutiveDaysTracking: map['consecutiveDaysTracking'],
      totalDaysTracking: map['totalDaysTracking'],
      completedCheckups: map['completedCheckups'],
      totalCheckups: map['totalCheckups'],
      folicAcidComplianceRate: map['folicAcidComplianceRate'],
      averageCycleRegularity: map['averageCycleRegularity'],
      lastProgressUpdate: DateTime.parse(map['lastProgressUpdate']),
    );
  }

  // 获取整体进度百分比
  int getOverallProgressPercentage() {
    // 综合考虑多个因素计算进度
    final trackingProgress = totalDaysTracking > 0 ? (totalDaysTracking / 180 * 100) : 0; // 假设6个月为完整跟踪期
    final checkupProgress = totalCheckups > 0 ? (completedCheckups / totalCheckups * 100) : 0;
    final regularityScore = averageCycleRegularity * 100;
    final complianceScore = folicAcidComplianceRate * 100;
    
    // 权重分配
    return ((trackingProgress * 0.3) + (checkupProgress * 0.3) + 
            (regularityScore * 0.2) + (complianceScore * 0.2)).round();
  }
}

// 备孕日历日模型
class FertilityCalendarDay {
  final DateTime date;
  final bool isToday;
  final bool isPredictedOvulation;
  final bool isFertile;
  final bool isPeriod;
  final double pregnancyProbability; // 0-100
  final BasalBodyTemperature? temperature;
  final OvulationTest? ovulationTest;
  final CervicalMucus? cervicalMucus;
  final Intercourse? intercourse;
  final FolicAcidIntake? folicAcid;

  FertilityCalendarDay({
    required this.date,
    this.isToday = false,
    this.isPredictedOvulation = false,
    this.isFertile = false,
    this.isPeriod = false,
    this.pregnancyProbability = 0.0,
    this.temperature,
    this.ovulationTest,
    this.cervicalMucus,
    this.intercourse,
    this.folicAcid,
  });

  // 获取日期状态文本
  String getStatusText() {
    if (isPeriod) return '经期';
    if (isPredictedOvulation) return '排卵日';
    if (isFertile) return '易孕期';
    return '非易孕期';
  }

  // 获取日期状态颜色
  Color getStatusColor() {
    if (isPeriod) return Colors.red.shade400;
    if (isPredictedOvulation) return Colors.pink.shade600;
    if (isFertile) {
      // 根据受孕概率调整颜色深度
      if (pregnancyProbability > 20) return Colors.purple.shade500;
      return Colors.purple.shade300;
    }
    return Colors.grey.shade200;
  }

  // 获取受孕概率文本
  String getProbabilityText() {
    if (pregnancyProbability < 5) return '极低';
    if (pregnancyProbability < 10) return '较低';
    if (pregnancyProbability < 20) return '中等';
    if (pregnancyProbability < 30) return '较高';
    return '非常高';
  }
}